package com.online.usermanagesystem.Interceptor;

import com.online.usermanagesystem.controller.SessionManageController;
import com.online.usermanagesystem.entity.Employee;
import com.online.usermanagesystem.entity.Session;
import com.online.usermanagesystem.service.EmployeeManageService;
import com.online.usermanagesystem.service.SessionManageService;
import com.online.usermanagesystem.utils.ConcurrentLRUMap;
import com.online.usermanagesystem.utils.DefaultResult;
import com.online.usermanagesystem.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限认证拦截器
 *
 * @author dragon
 */

@Component
public class AccessibleInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private SessionManageService sessionManageService;

    @Autowired
    private EmployeeManageService employeeManageService;

    private ConcurrentLRUMap<Integer, Employee> LRUMap = new ConcurrentLRUMap(65535);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        //拦截http请求
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        //检查Token有效性
        //过滤会话接口
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        if(handlerMethod.getBeanType() == SessionManageController.class) {
            return true;
        }

        String token = request.getParameter("token");
        if (null == token) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }

        Object obj = sessionManageService.find(token);
        if (null == obj) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return false;
        }

        if (!ResultUtil.isSuccess(obj)) {
            response.setStatus(((DefaultResult) obj).getCode());
            return false;
        }

        //路径权限检查
        Integer id = ((Session) obj).getId();
        Employee employee = LRUMap.get(id);
        if(null == employee) {
            obj = employeeManageService.query(id);
            if (!ResultUtil.isSuccess(obj)) {
                response.setStatus(((DefaultResult) obj).getCode());
                return false;
            }

            employee = (Employee)obj;

            //保存雇员信息
            LRUMap.put(id, employee);
        }

        return true;
    }
}
